var express = require('express')
var router = express.Router()

const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog') 
const {SuccessModel,  ErrorModel} = require('../model/resModel')
const loginCheck = require('../middleware/loginCheck')
router.get('/list', (req, res, next) => {
    let author = req.query.author || ''
    const keyword = req.query.keyword || ''

    if(req.query.isadmin) {
      console.log('isAdmin')
      // 管理员界面
      if(!req.session.username) {
        // 未登录
        res.json(
          new ErrorModel('未登录')
        )
        return
      }
      // 强制查询自己的博客
      author = req.session.username
    }
   
    return getList(author, keyword).then(listData => {
      res.json(
        new SuccessModel(listData)
      ) 
    })
})

router.get('/detail', (req, res, next)=> {
  return getDetail(req.query.id).then(data => {
    res.json(new SuccessModel(data))
  })
})

router.post('/new', loginCheck, (req, res, next) => {
  req.body.author = req.session.username
  return newBlog(req.body).then(data => {
    res.json(new SuccessModel(data))
  })
})

router.post('/update', loginCheck, (req, res, next) => {
  return updateBlog(req.query.id, req.body).then(val => {
    if(val) {
      res.json(new SuccessModel())
    } else {
      res.json(new ErrorModel('更新博客失败'))
    }
  })
})

router.post('/del', loginCheck, (req, res, next) => {
  const author = req.session.username
  return delBlog(req.query.id, author).then(val => {
    if(val) {
      res.json(new SuccessModel())
    } else {
      res.json(new ErrorModel('删除博客失败')) 
    }
  })
})


module.exports = router